package com.ligongzzz.rssicollector;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    WifiManager wifiManager;
    boolean requestWifiScan = false;
    String CSVStr = "";
    String currentFilePath = "";
    Integer ScanCNT = 4, currentCNT = 0, randomID = 0;
    BluetoothAdapter mBluetoothAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wifiManager = (WifiManager)getApplicationContext().getSystemService(WIFI_SERVICE);

        BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context c, Intent intent) {
                boolean success = intent.getBooleanExtra(
                        WifiManager.EXTRA_RESULTS_UPDATED, false);
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(bluetoothDevice != null) {
                    if(bluetoothDevice.getName()==null || !bluetoothDevice.getName().startsWith("HUAWEI")){
                        return;
                    }
                    short rssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);
                    Log.e("BT", bluetoothDevice.getName() + "," + bluetoothDevice.getAddress()+","+rssi);
                    Toast.makeText(MainActivity.this, String.valueOf(rssi), Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!requestWifiScan){
                    return;
                }
                else{
                    requestWifiScan = false;
                }
                if (success) {
                    onRSSISuccess(c);
                }
                else{
                    Toast.makeText(c, "Scan Failed!", Toast.LENGTH_SHORT).show();
                }
            }
        };

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(wifiScanReceiver, intentFilter);

        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "BL not supported!", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }


    }

    public static String getFormatTimeString() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd-HHmmss");
        return df.format(new Date());
    }


    public void onRSSISuccess(Context c){
        //Toast.makeText(c, "扫描成功！", Toast.LENGTH_SHORT).show();
        List<ScanResult> scanWifiList = wifiManager.getScanResults();
        List<Pair<String, Integer>> wifiRSSIList = new ArrayList<>();
        Log.e("WIFI SIZE:",String.valueOf(scanWifiList.size()));
        String RSSIResultStr = "";

        // Get X,Y data.
        Integer currentX = 0;
        try{
            EditText editTextX = (EditText)findViewById(R.id.XEditText);
            currentX = Integer.valueOf(editTextX.getText().toString());
        }
        catch(Exception e){
            e.printStackTrace();
            Toast.makeText(c, "坐标信息获取异常，请检查！", Toast.LENGTH_SHORT).show();
            return;
        }

        RSSIResultStr += "WIFI数量:"+scanWifiList.size()+" 位置："+currentX+ "\n";
        String CSVResultStr = "";

        if (scanWifiList != null && scanWifiList.size() > 0) {
            //设置随机数
            if(currentCNT==0) {
                randomID = (int) (1 + Math.random() * 100000000);
            }

            for (int i = 0; i < scanWifiList.size(); i++) {
                ScanResult scanResult = scanWifiList.get(i);
                if (!scanResult.SSID.isEmpty()) {
                    String key = "SSID:"+scanResult.SSID + " MAC:" + scanResult.BSSID;
                    wifiRSSIList.add(new Pair<String, Integer>(key, scanResult.level));
                    RSSIResultStr += key +" RSSI:" +String.valueOf(scanResult.level) + "\n";
                    CSVResultStr += randomID + "::" + scanResult.SSID;
                    CSVResultStr += "::" + scanResult.BSSID + "::" +scanResult.level;
                    CSVResultStr += "::" + currentX + "\n";
                }
            }
            CSVStr += CSVResultStr;

            TextView textView=(TextView)findViewById(R.id.text1);
            textView.setText(RSSIResultStr);

            currentCNT += 1;
            if(currentCNT < ScanCNT){
                sendScanSignal();
            }
            else{
                saveCSV(c);
            }
        }else {
            Toast.makeText(c, "没有找到附近的WIFI信号。", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    public void saveCSV(Context c){
        if(currentFilePath==""){
            Toast.makeText(c, "未创建文件，请先创建文件", Toast.LENGTH_SHORT).show();
            return;
        }
        File fileToSave = new File(getApplicationContext().getExternalFilesDir(
                Environment.DIRECTORY_DOCUMENTS), currentFilePath);
        try{
            FileOutputStream fileOutputStream = new FileOutputStream(fileToSave, false);
            fileOutputStream.write(CSVStr.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        }
        catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(c, "文件保存失败！", Toast.LENGTH_SHORT).show();
        }
    }

    public void onGetRSSIClicked(View view){
        currentCNT = 0;
        sendScanSignal();
    }

    public void onCNTClicked(View view){
        EditText editText = (EditText)findViewById(R.id.CNTEditText);
        ScanCNT = Integer.valueOf(editText.getText().toString());
    }

    public void sendScanSignal(){
        WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(WIFI_SERVICE);
        if (wifiManager == null){
            Toast.makeText(this,"Failed to initialize wifi manager!", Toast.LENGTH_SHORT).show();
            return;
        }

        wifiManager.startScan();
        mBluetoothAdapter.startDiscovery();
        requestWifiScan = true;
        TextView textView=(TextView)findViewById(R.id.text1);
        textView.setText("进行第"+currentCNT+"/"+ScanCNT+"次扫描，请稍后...");
        //bluetoothScanSignal();
    }


    public void bluetoothScanSignal(){
        BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
        bluetoothLeScanner.startScan(new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, android.bluetooth.le.ScanResult result) {
                super.onScanResult(callbackType, result);
                Integer rssi = result.getRssi();
                String ssid = result.getDevice().getAddress();
                String name = result.getDevice().getName();
                Log.e("BLE", name+","+ssid+","+rssi.toString());
                if(name == null){
                    return;
                }
                Toast.makeText(MainActivity.this, name+","+ssid+","+rssi.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void onXPlusClicked(View view){
        EditText editText = (EditText)findViewById(R.id.XEditText);
        Integer editTextValue = 0;
        try {
            editTextValue = Integer.valueOf(editText.getText().toString());
        }
        catch (Exception e){
            e.printStackTrace();
        }
        editText.setText(String.valueOf(editTextValue+1));
    }

    public void onXMinusClicked(View view){
        EditText editText = (EditText)findViewById(R.id.XEditText);
        Integer editTextValue = 0;
        try {
            editTextValue = Integer.valueOf(editText.getText().toString());
        }
        catch (Exception e){
            e.printStackTrace();
        }
        if(editTextValue<=0){
            editTextValue=1;
        }
        editText.setText(String.valueOf(editTextValue-1));
    }

    public void onCreateFileClicked(View view){
        final EditText editText = new EditText(MainActivity.this);
        String tempFilePath = "RSSI" + getFormatTimeString() + ".csv";
        editText.setText(tempFilePath);

        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(MainActivity.this);
        inputDialog.setTitle("输入文件名").setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String editGetText = editText.getText().toString();
                        if (editGetText.equals("")){
                            Toast.makeText(MainActivity.this, "文件名不能为空！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        currentFilePath = editGetText;
                        CSVStr = "";
                        //File file = new File(getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), );
                        TextView textView = (TextView)findViewById(R.id.textFileInfo);
                        textView.setText("当前文件："+currentFilePath);
                    }
                });
        inputDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        inputDialog.show();
    }
}
